package com;

/**
 * @Description: TODO QQ1667847363
 * @author: xiao kun tai
 * @date:2021/11/1 15:32
 */


import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

import java.io.File;

/***
 * 批处理
 */
public class WordCount {
    public static void main(String[] args) throws Exception{
        ///创建执行环境
        ExecutionEnvironment env =ExecutionEnvironment.getExecutionEnvironment();


        /*File directory = new File("");//参数为空

        String courseFile = directory.getCanonicalPath() ;

        System.out.println(courseFile);*/

        String inputPath ="src/main/resources/test.txt";

        DataSet<String> inputDataSet = env.readTextFile(inputPath);

        DataSet<Tuple2<String, Integer>> resultSet = inputDataSet.flatMap(new MyFlatMapper())
                .groupBy(0)   //按照第一个位置的word分组
                .sum(1);//将第二个位置上的数据求和
        //输出
        resultSet.print();

    }
    //自定义类，实现FlatMapFunction
    public static  class MyFlatMapper implements FlatMapFunction<String, Tuple2<String,Integer>>{
        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> collector) throws Exception {
            //按空格分词
            String[] words = value.split(" ");
            //遍历所有word，包成二元组输出
            for (String word : words) {
                collector.collect(new Tuple2<String, Integer>(word, 1));
            }
        }
    }
}
